import Taro from "@tarojs/taro";
import avatar from "../assets/img/common/avatar.png";
import { UserOutput } from '../api/api'
/**
 * 系统公共数据
 */
export const companyName = '渔满天下'
export const servicePhone = '400-874-1688'
// export const serverHost = 'http://192.168.3.161:8110/'
 export const serverHost = 'http://ymtx.ynxbgg.net/'
//export const serverHost = 'http://www.ynlnyy.cn/'

export const uploadPath = '/api/services/app/configuration/Upload'
export const pageSize = 10;
/** 手机号验证正则 */
export const phoneReg = /^0?(13|14|15|18|17)[\d]{9}$/;
/** 不能以空格开头 */
export const spaceReg = /^[^\s]+/;
/** 不能有中文字符 */
export const zhCNReg = /^[\x00-\xff]*$/;
/** 数字正则 */
export const numberReg = /^[0-9]*$/;
// 字母正则
export const letterReg = /[a-zA-Z]/;
/** 身份证号 */
export const IDCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
// 银行卡号
export const CardReg = /^([1-9]{1})(\d{15}|\d{18})$/;
export const userSexArr = ['男','女','保密']; // 1 = Man , 2 = Women , 3 = UnKnow

export const banks = ['中国人民银行','国家开发银行','中国进出口银行','中国农业发展银行','中国工商银行','中国农业银行','中国银行','中国建设银行','交通银行','中国邮政储蓄银行',
  '中国光大银行','中国民生银行','招商银行','华夏银行','中信银行','上海浦东发展银行','平安银行','广发银行','兴业银行','浙商银行','渤海银行','恒丰银行']
/**
 * 当前系统对应公共数据
 */
export enum userType { '会员' = 1, 'VIP会员', '合伙人' }
export interface userInfoInterface extends UserOutput{}
// 文章列表请求类型
export const articleType = {
  dynamic: '3183bb2c-3a90-4872-270c-08d7937c9e4a',
  aboutus: 'b01b40e1-0d63-4395-69af-08d79409978f',
  help: 'c0dc6544-1343-4f0d-337c-08d7941dc3aa',
  signRule: '83b06743-ff3d-47d7-b3ac-08d796710a66', // 签到规则文章ID
  userServiceAg: 'effd11bf-7824-4c73-588b-08d796653134', // 用户服务协议
  userPrivacy: 'd891a143-8516-451f-3f5e-08d794a23864', // 用户隐私政策
}
export const memberTypeArr = [
  { id: '00000000-0000-0000-0000-000000000000', title: '游客' },
  { id: '6b900096-34a6-410b-060c-08d794ca24e8', title: '初级联养' },
  { id: '3aa8fffc-ebf9-43da-db7a-08d7957eee0a', title: '中级联养' },
  { id: '00eee36b-0f64-412b-db79-08d7957eee0a', title: '高级联养' }
  ]; // 用户类型

/**
 * 系统公共方法
 */
export const showToast = ( title: string ) => {
  Taro.showToast({ title, icon: 'none' })
}

export const showModel = ( title: string, content: string, confirmText: string = '确定', callBack, errorBack?   ) => {
  Taro.showModal({
    title,
    content,
    confirmText,
    confirmColor: '#409fff'
  }).then(res => {
    if(res.confirm) {
      callBack()
    }
    else { errorBack && errorBack() }
  })
}

export const setUserInfo = (info?: any) => {
  Taro.setStorageSync("user", info ? JSON.stringify(info) : "");
}

// 获取用户信息
export const getUserInfo = () => {
  var data = Taro.getStorageSync("user") || {};
  return Object.keys(data).length > 0 ? JSON.parse(data) : ''
}

// 更新用户信息
export const updateUserInfo = (field: string, value: string) => {
  var data: userInfoInterface = JSON.parse(Taro.getStorageSync("user")) || {};
  data[field] = value
  setUserInfo(data)
}

// 获取token
export const getToken = () => {
  const user = getUserInfo() || {};
  if(Object.keys(user).length <= 0 ) return ''
  return {Authorization: "Bearer " + user.token};
  // return { Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxOTFCMzhEQjNGNzIwODRCMjI1MUQyOTA3MTQxREUxNjcwMjZFOTVBQkNDQUJGQzJBNzBEM0RFNDQyQTQ5MjlCRjU1RkM4NTU1RjlGODhDQyIsImlhdCI6IjE1Nzg3MTI4MTIiLCJuYmYiOiIxNTc4NzEyODEyIiwiZXhwIjoiMTU3ODc5OTIxMiIsImlzcyI6IkFQSSIsImF1ZCI6IlVzZXIiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4ifQ.vs3Ia-raWwSshsXZ_b9AvGgukmPn-N6glDy71i4Tfzo"}
}

export const navigateTo = (url: string) => {

  let pagesArr = Taro.getApp().state.pagesArr || []
  let hashUrl = url.includes('?') ? url.split('?')[0] : url
  // if(hashUrl.includes('?')) { hashUrl.split('?')[0] }
  let userInfo = getUserInfo()
  // console.log(url)
  pagesArr.map(item => {
    if('/'  + item.path === hashUrl ) {
      if(item.isLogin && Object.keys(userInfo).length <= 0) {
        Taro.navigateTo({ url: `/pages/index/index?random=${Math.random()}` });
      } else if (item.isLogin && !userInfo.userPhone) {
        Taro.navigateTo({ url: `/pages/login/login?random=${Math.random()}` });
      } else {
        url = url.includes('?')?`${url}&random=${Math.random()}`:`${url}?random=${Math.random()}`
        Taro.navigateTo({ url })
      }
    }
  })
}

export const navigateBack = (delta: number = 1) => {
  Taro.navigateBack({ delta })
}

export const redirectTo = (url: string) => {
  Taro.redirectTo({ url })
}

export const stringPartOf = (str: string, length: number) => {
  if(!str) return str
  let len = str.length
  if(len <= length) return str
  return str.substr(0, length) + '...'
}

export const phonePartOf = (phone: string) => {
  if(!phone) return phone;
  return phone.substr(0, 3) + '****' + phone.substr(-4)
}

export const namePartOf = (name: string) => {
  if(!name) return name;
  let len = name.length
  if(len < 2) return  name
  else if(len === 2) { return name.substr(0, 1) + '*' }
  else { return name.substr(0, 1) + '*'.repeat(len-2) + name.substr(-1) }
}

export const cardNumPartOf = (value?: string, ) => {
  var cardNum = value || "";
  return "*** **** **** **** " + cardNum.substr(-4);
}

// 小于0的数字加0补全
export const formatNumber = (value: number) => {
  if(typeof value !== 'number') return value
  if(value >= 1 && value < 10) { return '0' + value }
  return value
}

// 后台返回的时间截取
export const subTime = (time: string) => {
  time = time ? time: ''
  let pos = time.indexOf('T')
  if(pos !== -1){
    let temp = time.replace('T', ' ')
    return temp.substr(0, 19)
  }else {
    return time
  }
}

export const getTime = () =>{}

export const  getAvatar = (src: string) => {
  return src || avatar
}

// 图片预览
export const imgPreView = (imgPath: any) => {
  let imgArr = imgPath
  if (typeof imgArr !== 'object'){ imgArr = [imgPath] }
  Taro.previewImage({
    urls: imgArr,
    current: '0'
  })
}

export const setStorage = (key: string, value?: object) => {
  Taro.setStorageSync(key, value ? JSON.stringify(value) : "");
}

export const getStorage = (key: string) => {
  var data = Taro.getStorageSync(key);
  return data ? JSON.parse(data) : null
}

export const isNumber = (str: string) => {
  let reg = new RegExp(numberReg)
  return reg.test(str)
}

export const isLetter = (str: string) => {
  return new RegExp(letterReg).test(str)
}

export const isPhone = (str: string) => {
  let reg = new RegExp(phoneReg)
  return reg.test(str)
}

export const isIDCard = (str: string) => {
  let reg = new RegExp(IDCardReg)
  return reg.test(str)
}

export const isBankCard = (str: string) => {
  let reg = new RegExp(CardReg)
  return reg.test(str)
}

// 图片上传
export const imgUpload = (callBack) => {
  Taro.chooseImage({
    sourceType: ['album', 'camera'],
    count: 1,
    sizeType: ['compressed'], // 图片尺寸，选项原图和压缩， h5端未实现压缩
  }).then(res => {
    let tempFiles = res.tempFiles[0]
    // 压缩图片
    // console.log(res)
    Taro.showLoading({ title: '图片上传中...' })
    this.imgCompressed(tempFiles.path, tempFiles.size, (blobFile) => {
      Taro.uploadFile({
        url: serverHost + uploadPath,
        filePath: blobFile,
        name: 'file',
        header: getToken()
      }).then(imgRes => {
        Taro.hideLoading()
        if(imgRes.statusCode != 200) { showToast('上传图片失败,错误原因: ' + imgRes.errMsg); return }
        // 图片正确上传
        let imgPath = JSON.parse(imgRes.data).result
        callBack && callBack(imgPath)
      }).catch(err1 => {
        Taro.hideLoading()
        console.error(err1)
        showToast('上传图片失败,请稍后重试~')
      })
    })
  }).catch(err => {
    console.error(err)
    showToast('打开图片失败,请稍后重试~')
  })
}

// 图片压缩
export const imgCompressed = (imgPath: string, imgSize: number, callBack?) => {
  let quality = 1
  // 大于1M的压缩
  let sizeM = imgSize / 1024 / 1024
  console.log(sizeM)
  if(sizeM < 1 ) {
    // 不压缩
    quality = 1
    callBack(imgPath)
    return
  }
  else if(sizeM >= 1 && sizeM < 2) { quality = 0.95 }
  else if(sizeM >= 2 && sizeM < 3) { quality = 0.92 }
  else { quality = 0.8 }
  let image = document.createElement('img')
  image.crossOrigin = 'Anonymous'
  console.log(image)
  image.onload = function () {
    let canvas = document.createElement("canvas")
    canvas.width = image.width
    canvas.height = image.height
    let ctx = canvas.getContext("2d")
    ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
    /**
     * 1、本来打算使用toBlob函数进行压缩，因为Taro的chooseImage函数返回的图片路径是blob类型的文件，可是toBlob函数不知道什么原因，并不能返回blob文件。于是打算转换成base64
     * 的图片，没想到也是可以上传的
     * 2、后来真机测试发觉想太多，在pc上能上传，但在手机上并不能上传，还是得转化成blob文件
     *
     */
    // 转化成blob文件
    // 第一个参数回调，第二个参数图片类型(image/png; image/jpeg)默认为image/png；第三个参数图片质量（0~1）取值
    canvas.toBlob((blobFile) => {
      // console.log(blobFile)
      // blob数据转化成url数据
      let url = URL.createObjectURL(blobFile)
      // console.log(url)
      callBack&&callBack(url)
    }, 'image/jpeg', quality)

    /*let dataUrl = canvas.toDataURL('image/jpeg', quality)
    if(!dataUrl) { showToast('图片上传压缩失败, 请重试！'); return }
    callBack&&callBack(dataUrl)*/
  }
  image.src = imgPath
}


export const wxPay = (payParams, callback: (res) => void) => {
  Taro.requestPayment({
    timeStamp: payParams.timeStamp,
    nonceStr: payParams.nonceStr,
    package: payParams.package,
    signType: payParams.signType,
    paySign: payParams.paySign,
  }).then(res => { callback(res) })
    .catch(res => { console.log(res); showToast('支付失败') })
}

export const makePhoneCall = (phoneNumber: string = servicePhone) => {
  Taro.makePhoneCall({
    phoneNumber: phoneNumber,
  })
}

export const getWechatCode = () => {
  let url = serverHost + '/wechat/GetWechatCode'
  window.location.href = url
}

export const wxH5Pay = (payParams, callback: () => void) => {
  // alert(JSON.stringify(payParams));
  if (typeof window['WeixinJSBridge'] == "undefined") {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady',
        () => onBridgeReady(payParams, callback), false);
    } else if (document['attachEvent']) {
      document['attachEvent']('WeixinJSBridgeReady',
        () => onBridgeReady(payParams, callback));
      document['attachEvent']('onWeixinJSBridgeReady',
        () => onBridgeReady(payParams, callback));
    }
  } else {
    onBridgeReady(payParams, callback);
  }
}

/**
 *  微信支付
 */
const onBridgeReady = (payParams, callback: () => void) => {
  const that = this;
  window['WeixinJSBridge'].invoke(
    'getBrandWCPayRequest',
    payParams,
    function (res) {
      if (res.err_msg == "get_brand_wcpay_request:ok") {
        callback();
      } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
        that.showToast("支付取消");
      } else if (res.err_msg == "get_brand_wcpay_request:fail") {
        that.showToast('支付失败');
      }
    }
  );
}


